package com.zhang.code.service.impl;

import com.zhang.code.dao.SysAuthCodeDao;
import com.zhang.code.pojo.po.SysAuthCodePo;
import com.zhang.dubbo.api.code.CodeRpcApi;
import com.zhang.dubbo.api.email.EmailRpcApi;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;


@Service(timeout = 20000)
@Component
public class CodeServiceImpl implements CodeRpcApi {

    @Autowired
    private SysAuthCodeDao sysAuthCodeDao;

    @Reference
    private EmailRpcApi emailRpcApi;

    @Override
    public String genCode(String email) {
        int codeNum = ThreadLocalRandom.current().nextInt(100000, 999999);
        String code = String.valueOf(codeNum);
        LocalDateTime genTime = LocalDateTime.now();
        LocalDateTime expireTime = genTime.plusSeconds(60);

        SysAuthCodePo po = new SysAuthCodePo();
        po.setCreateTime(genTime);
        po.setExpireTime(expireTime);
        po.setCode(code);
        po.setEmail(email);

        SysAuthCodePo sysAuthCodePo = sysAuthCodeDao.save(po);

        if (Objects.nonNull(sysAuthCodePo.getId())){
            return emailRpcApi.sendSimple(email,"VerCode", code);
        }else {
            return "code generate is fail";
        }
    }

    @Override
    public String checkCode(String email, String code) {
        SysAuthCodePo po = new SysAuthCodePo();
        po.setCode(code);
        po.setEmail(email);

        Example<SysAuthCodePo> example = Example.of(po);
        Sort sort = new Sort(Sort.Direction.DESC,"id");
        List<SysAuthCodePo> pos = sysAuthCodeDao.findAll(example,sort);
        if (pos.isEmpty()){
            return "code is not exist";
        }
        SysAuthCodePo codePo = pos.get(0);
        LocalDateTime now = LocalDateTime.now();
        if (now.isAfter(codePo.getExpireTime())){
            return "code is expire";
        }
        if (codePo.getCode().equals(code)){
            return "true";
        }else {
            return "code is error";
        }
    }


}
